<template>
  <div class="audit_user">
    <a-modal
      :title="title"
      :centered="true"
      :width="700"
      wrapClassName="common_modal add_doctor_modal"
      v-model:open="visible"
      :confirm-loading="confirmLoading"
      okText="确定"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        ref="editFormRef"
        :model="formInfo"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="医院" name="hospId">
          <a-select
            v-model:value="formInfo.hospId"
            show-search
            :filter-option="filterOption"
            @change="getDeptOption"
            popupClassName="common_select_dropdown"
          >
            <a-select-option v-for="item in props.hospList" :value="item.id" :key="item.id">
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="科室" name="deptId">
          <a-select
            v-model:value="formInfo.deptId"
            allowClear
            show-search
            :filter-option="filterOption"
            popupClassName="common_select_dropdown"
          >
            <a-select-option v-for="item in deptList" :value="item.value" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="医师姓名" name="doctorName">
          <a-input v-model:value="formInfo.doctorName" />
        </a-form-item>
        <a-form-item label="医师扩展码" name="doctorExtendCode">
          <a-input v-model:value="formInfo.doctorExtendCode" />
        </a-form-item>
        <a-form-item label="医师职称" name="doctorGrade">
          <a-select
            v-model:value="formInfo.doctorGrade"
            show-search
            :filter-option="filterOption"
            popupClassName="common_select_dropdown"
          >
            <a-select-option v-for="item in props.levelList" :value="item.value" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="医师学历" name="doctorDegree">
          <a-select
            v-model:value="formInfo.doctorDegree"
            show-search
            :filter-option="filterOption"
            popupClassName="common_select_dropdown"
          >
            <a-select-option v-for="item in props.degreeList" :value="item.value" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="出生日期" name="doctorBirthday" :autoLink="false">
          <a-input-group compact style="width: 100%">
            <a-select
              style="width: 33%"
              placeholder="年"
              v-model:value="checkYear"
              allowClear
              show-search
              :filter-option="filterOption"
              popupClassName="common_select_dropdown"
            >
              <a-select-option v-for="item in yearList" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-select
              style="width: 33%"
              placeholder="月"
              v-model:value="checkMonth"
              allowClear
              show-search
              :filter-option="filterOption"
              popupClassName="common_select_dropdown"
            >
              <a-select-option v-for="item in monthList" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
            <a-select
              style="width: 33%"
              placeholder="日"
              v-model:value="checkDate"
              allowClear
              show-search
              :filter-option="filterOption"
              popupClassName="common_select_dropdown"
            >
              <a-select-option v-for="item in dateList" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { filterOption } from '@/utils/filter_util'
import { doctorUpdate, doctorSave } from '@/axios/api/doctor_api'
import { getDeptList } from '@/axios/api/options_api'
import { ref, watch } from 'vue'
import type { ListType } from '@/axios/api/type'
import type { EditFromType } from './type'
import moment from 'moment'
import { cloneDeep } from 'lodash-es'
import { editProps } from './props'
import { message } from 'ant-design-vue'

const [messageApi] = message.useMessage()
const emit = defineEmits(['getPage'])
const props = defineProps(editProps)
const title = ref('')
const editFormRef = ref()
const endYear = moment().year()
// 获取当前日期一百年前的年份
let startYear = moment().subtract(100, 'years').year()
const yearList = ref<ListType[]>([])
while (startYear <= endYear) {
  yearList.value.push({ value: startYear.toString(), label: startYear.toString() })
  startYear++
}
const monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
const dateOption = [
  '01',
  '02',
  '03',
  '04',
  '05',
  '06',
  '07',
  '08',
  '09',
  '10',
  '11',
  '12',
  '13',
  '14',
  '15',
  '16',
  '17',
  '18',
  '19',
  '20',
  '21',
  '22',
  '23',
  '24',
  '25',
  '26',
  '27',
  '28',
  '29',
  '30',
  '31'
]
const dateList = ref<string[]>([])
const deptList = ref<ListType[]>([])
const checkYear = ref('')
const checkDate = ref('')
const checkMonth = ref('')
const visible = ref(false)
const confirmLoading = ref(false)

const rules = {
  hospId: [{ required: true, message: '请选择医院', trigger: ['change', 'blur'] }],
  doctorName: [{ required: true, message: '请填写医生姓名', trigger: ['change', 'blur'] }],
  doctorBirthday: [{ validator: validateDate, trigger: ['blur', 'change'] }]
}
const formInfo = ref<EditFromType>({
  doctorName: '',
  doctorExtendCode: '',
  hospId: '',
  doctorDegree: '',
  doctorGrade: '',
  doctorBirthday: '',
  deptId: ''
})
const record = ref<any>({})
const editType = ref('add')
const monthWatch = watch(checkMonth, (val) => {
  if (checkYear.value && checkMonth.value) {
    let num = moment(checkYear.value + '-' + checkMonth.value).daysInMonth()
    let list = dateOption.filter((item) => Number(item) <= num)
    dateList.value = list
  } else {
    dateList.value = dateOption
  }
})
function validateDate() {
  if (checkDate.value || checkMonth.value || checkYear.value) {
    if (!(checkYear.value && checkMonth.value && checkDate.value)) {
      return Promise.reject('请填写完整的日期')
    } else {
      return Promise.resolve()
    }
  } else {
    return Promise.resolve()
  }
}
function showModal(type: string, info: any) {
  if (type === 'add') {
    title.value = '新增医师信息'
    editType.value = 'add'
  } else {
    title.value = '修改医师信息'
    editType.value = 'update'
    getInfo(info)
  }
  visible.value = true
  record.value = info
}
function getInfo(record: any) {
  Object.keys(formInfo.value).forEach((item) => {
    console.log(
      '%c [ item ]-242',
      'font-size:13px; background:pink; color:#bf2c9f;',
      item,
      record,
      record[item]
    )
    formInfo.value[item as keyof EditFromType] = record[item] || ''
  })
  if (record.hospId) {
    getDeptOption(record.hospId)
  }
  if (record.doctorBirthday) {
    let list = record.doctorBirthday.split('-')
    checkDate.value = list[2]
    checkMonth.value = list[1]
    checkYear.value = list[0]
  }
}
function getDeptOption(val: string) {
  getDeptList({ hospKey: val }).then((res) => {
    deptList.value = res.data || []
    let info = deptList.value.find((item) => item.value === formInfo.value.deptId)
    if (info) {
      console.log('%c [ info ]-231', 'font-size:13px; background:pink; color:#bf2c9f;', info)
      formInfo.value.deptId = info.value
    } else {
      formInfo.value.deptId = ''
    }
  })
}
function handleOk() {
  editFormRef.value.validate().then(() => {
    confirmLoading.value = true
    let formContent = cloneDeep(formInfo.value)
    formContent.doctorBirthday =
      checkYear.value && checkMonth && checkDate
        ? `${checkYear.value}-${checkMonth.value}-${checkDate.value}`
        : ''
    if (editType.value === 'update') {
      formContent.id = record.value.id
      doctorUpdate(formContent)
        .then((res) => {
          if (res.code === 200) {
            messageApi.success(res.msg)
            emit('getPage')
            handleCancel()
          }
        })
        .finally(() => {
          confirmLoading.value = false
        })
    } else {
      doctorSave(formContent)
        .then((res) => {
          if (res.code === 200) {
            messageApi.success(res.msg)
            emit('getPage')
            handleCancel()
          }
        })
        .finally(() => {
          confirmLoading.value = false
        })
    }
  })
}
function handleCancel() {
  visible.value = false
  formInfo.value = {
    doctorName: '',
    hospId: '',
    doctorDegree: '',
    doctorGrade: '',
    doctorBirthday: '',
    deptId: '',
    doctorExtendCode: ''
  }
}
defineExpose({
  showModal
})
</script>
